package com.diligent.cloud.sfc.resources.impl;

import com.alibaba.fastjson.JSON;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ListResult;
import com.diligent.cloud.primary.data.model.Result;
import com.diligent.cloud.sfc.factory.impl.WearStripsStation;
import com.diligent.cloud.sfc.model.OrderType;
import com.diligent.cloud.sfc.model.WearStripsDpsOrder;
import com.diligent.cloud.sfc.resources.WoDpsResource;
import com.diligent.cloud.sfc.service.DpsService;
import com.diligent.cloud.sfc.service.ISfcService;
import com.diligent.cloud.sfc.service.WorkshopScenePackingService;
import com.diligent.cloud.sfc.service.impl.WipServiceImpl;
import com.diligent.cloud.wip.panel.modle.WipStorageLedger;
import com.diligent.cloud.workorder.model.DpsListParams;
import com.diligent.cloud.workorder.model.WoOrder;
import com.diligent.cloud.workorder.service.WoOrderFeignService;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RestController
public class WoDpsResourceImpl implements WoDpsResource {
    private final DpsService dpsService;
    private final WearStripsStation wearStripsStation;
    private final ISfcService sfcService;
    private final WoOrderFeignService orderFeignService;
    private final WipServiceImpl wipServiceImpl;
    private final WorkshopScenePackingService workshopScenePackingService;

    public WoDpsResourceImpl(DpsService dpsService, WearStripsStation wearStripsStation, ISfcService sfcService,
                             WoOrderFeignService orderFeignService, WipServiceImpl wipServiceImpl,
                             WorkshopScenePackingService workshopScenePackingService) {
        this.dpsService = dpsService;
        this.wearStripsStation = wearStripsStation;
        this.sfcService = sfcService;
        this.orderFeignService = orderFeignService;
        this.wipServiceImpl = wipServiceImpl;
        this.workshopScenePackingService = workshopScenePackingService;
    }

    @Override
    public ResponseEntity<ListResult> selectDpsList(DpsListParams dpsListParams) {
        if (OrderType.后加工工单.equals(dpsListParams.getOrderType())) {
            List<WearStripsDpsOrder> answer = new ArrayList<>();
            WearStripsDpsOrder wearStripsDpsOrder;
            ResponseEntity<ListResult> dpsListResult = dpsService.selectDpsList(dpsListParams);

//            for (LinkedHashMap orderMap : (ArrayList<LinkedHashMap>) dpsListResult.getBody().getData()) {
//
//                long time3 = System.currentTimeMillis();
//                wearStripsDpsOrder = new WearStripsDpsOrder();
//                WoOrder order = JSON.parseObject(JSON.toJSONString(orderMap), WoOrder.class);
//
//                BeanUtils.copyProperties(order, wearStripsDpsOrder);
//
//                Integer  totalDigit = 0;
//                for (int i = 0 ; i < order.getSonMatNeedNum().size();i++){
//                    BigDecimal demand = order.getSonMatNeedNum().get(i);
//                    String mat = order.getSonMatNeed().get(i);
//
//                    int stock = ((WipStorageLedger) (wipServiceImpl.getInventoryByMatCodeAndCwocCode
//                            (mat,
//                                    order.getWorkCenterCode(), null, order.getSystemId())
//                            .getBody().getData())).getDigit().intValue();
//                    totalDigit += stock / demand.intValue();
//                }
//                long time4 = System.currentTimeMillis();
//              //  System.out.println("当前程序耗时：" + (time4 - time3) + "ms");
//                wearStripsDpsOrder.setSubMat(wearStripsDpsOrder.getSonMatNeed());
//                wearStripsDpsOrder.setMatchingRate((totalDigit / order.getSonMatNeedNum().size()) * 100);
//                wearStripsDpsOrder.setMatchingDigit(wearStripsDpsOrder.getSonMatNeedNum());
//                wearStripsDpsOrder.setMatCodes(Collections.singletonList(order.getCv7()));
//                wearStripsDpsOrder.setDemandDigit(Collections.singletonList(order.getCv7Num()));
//                wearStripsDpsOrder.setStockDigit(Collections.singletonList(((WipStorageLedger) (wipServiceImpl.getInventoryByMatCodeAndCwocCode
//                        (order.getCv7(),
//                                order.getWorkCenterCode(), null, order.getSystemId())
//                        .getBody().getData())).getDigit().intValue()));
//                answer.add(wearStripsDpsOrder);
//            }
            try {
                threadPool(dpsListResult.getBody().getData(),answer);
            } catch (Exception e) {
                e.printStackTrace();
            }

            ListResult result = new ListResult(answer);
            result.modifyCode(Codes.success.getCode(), dpsListResult.getBody().getMsg());
            return ResponseEntity.ok(result);
        } else if (OrderType.包装工单.equals(dpsListParams.getOrderType())) {
            ResponseEntity<ListResult> dpsList = dpsService.selectDpsList(dpsListParams);
            return ResponseEntity.ok(workshopScenePackingService.getPackDpsFilter(dpsListParams,dpsList));
        }else{
            return dpsService.selectDpsList(dpsListParams);
        }
    }



    @Override
    public ResponseEntity<Result> updateDps(Long dpsId) {
        return dpsService.updateDps(dpsId);
    }

    private void test1(WoOrder order, List<WearStripsDpsOrder> answer) {
        long time3 = System.currentTimeMillis();
        WearStripsDpsOrder  wearStripsDpsOrder = new WearStripsDpsOrder();

        BeanUtils.copyProperties(order, wearStripsDpsOrder);

        Integer  totalDigit = 0;
        for (int i = 0 ; i < order.getSonMatNeedNum().size();i++){
            BigDecimal demand = order.getSonMatNeedNum().get(i);
            String mat = order.getSonMatNeed().get(i);

            int stock = ((WipStorageLedger) (wipServiceImpl.getInventoryByMatCodeAndCwocCode
                    (mat,
                            order.getWorkCenterCode(), null, order.getSystemId())
                    .getBody().getData())).getDigit().intValue();
            totalDigit += stock / demand.intValue();
        }
        long time4 = System.currentTimeMillis();
         System.out.println("当前程序耗时：" + (time4 - time3) + "ms");
        wearStripsDpsOrder.setSubMat(wearStripsDpsOrder.getSonMatNeed());
        wearStripsDpsOrder.setMatchingRate((totalDigit / order.getSonMatNeedNum().size()) * 100);
        wearStripsDpsOrder.setMatchingDigit(wearStripsDpsOrder.getSonMatNeedNum());
        wearStripsDpsOrder.setMatCodes(Collections.singletonList(order.getCv7()));
        wearStripsDpsOrder.setDemandDigit(Collections.singletonList(order.getCv7Num()));
        wearStripsDpsOrder.setStockDigit(Collections.singletonList(((WipStorageLedger) (wipServiceImpl.getInventoryByMatCodeAndCwocCode
                (order.getCv7(),
                        order.getWorkCenterCode(), null, order.getSystemId())
                .getBody().getData())).getDigit().intValue()));
        answer.add(wearStripsDpsOrder);
    }


    public void   threadPool(List<LinkedHashMap> maps, List<WearStripsDpsOrder> answer)  {

        //最大可用的CPU核数
        int PROCESSORS = Runtime.getRuntime().availableProcessors();
        //线程最大的空闲存活时间，单位为秒
        int KEEPALIVETIME = 60;
        //任务缓存队列长度
        int BLOCKINGQUEUE_LENGTH = 500;
        ThreadPoolExecutor executor = new ThreadPoolExecutor(PROCESSORS * 2, PROCESSORS * 4, KEEPALIVETIME,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(BLOCKINGQUEUE_LENGTH));

        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        final CountDownLatch countDownLatch=new CountDownLatch(maps.size());

        for (int i = 0; i < maps.size(); i++) {
            WoOrder order = JSON.parseObject(JSON.toJSONString(maps.get(i)), WoOrder.class);

            executor.execute(new Runnable() {
                                 @Override
                                 public void run() {
                                     try {
                                         test1(order, answer);
                                         Thread.sleep(500);
                                     } catch (InterruptedException e) {
                                         e.printStackTrace();
                                     }finally {
                                         countDownLatch.countDown();
//                                         System.out.println("线程池中线程数目：" + executor.getPoolSize() +
//                                                 "，队列中等待执行的任务数目：" + executor.getQueue().size() +
//                                                 "，已执行完毕的任务数目：" + executor.getCompletedTaskCount());
                                     }
                                 }
            });
        }
        try {
            //等待子线程全部结束
            countDownLatch.await();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }




}
